<?php

namespace app\common\model\merchant;

use app\common\model\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

/**
 * 商户积分商品
 * Class MerchantProductPoint
 * @package app\model
 */
class MerchantProductPointModel extends BaseModel
{
    //
    protected $name = 'merchant_product_point';


    // 设置字段信息
    protected $schema = [
        'id' => 'int',        // 序号
        'mer_id' => 'string',        // 商户编号
        'code' => 'string',        // 商品条码
        'title' => 'string',        // 商品名称
        'sub_title' => 'string',        // 副标题
        'class_id' => 'int',        // 分类ID
        'pics' => 'string',        // 商品主图
        'images' => 'string',        // 详情图
        'describe' => 'string',        // 描述
        'point' => 'int',        // 兑换积分
        'op_user' => 'int',        // 添加人
        'create_at' => 'datetime',        // 创建时间
        'update_at' => 'datetime',        // 更新时间
        'delete_at' => 'datetime',        // 删除时间
    ];

    /**
     * 根据商户ID和商品$id 获取商品的信息，用于前端显示
     * @param string $merID 商户编号
     * @param string $id 商户id
     * @return mixed
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function productInfo($where)
    {
        $info = $this->db()->where($where)->whereRaw('delete_at is null')
            ->field('id,title,sub_title,class_id,pics,point,stock_num,images,price,code,show_num')
            ->find();
        if (!empty($info['pics'])) {
            $info['pics'] = explode(',', $info['pics']);
        }
        if (!empty($info['images'])) {
            $info['images'] = explode(',', $info['images']);
        }
        return $info;
    }

    /**
     * 详情
     * @param $id
     * @return array|mixed|\think\facade\Db|\think\Model|null
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException|Exception
     */
    public function proInfo($id)
    {
        $data = $this->db()->alias('g')->join('product_class c', 'g.class_id=c.id')
            ->where('g.id', $id)->where('delete_at', null)
            ->field('g.id,g.code,g.title,g.sub_title,g.pics,g.images,g.mer_id,g.op_user,g.warn_num,
            c.title as class_title,c.id as class_id,g.describe')
            ->find();
        if (!$data) {
            throw new Exception('未找商品', API_ERROR);
        }
        $data['images'] = explode(',', $data['images']);
        return $data;
    }

    /**
     * 修改、添加
     * @param array $data
     * @return bool
     * @throws Exception
     * @throws \think\db\exception\DbException
     */
    public function proSave(array $data): bool
    {
        $id = empty($data['id']) ? 0 : $data['id'];
        if (isset($data['id'])) {
            unset($data['id']);
        }
        if (!empty($id)) {
            $where[] = ['id', '<>', $id];
        }
        //重复
        $cont = $this->db()->where($where ?? [])
            ->whereNull('delete_at')
            ->where('mer_id', $data['mer_id'])->whereRaw('code=:code or title=:title', ['code' => $data['code'], 'title' => $data['title']])
            ->count('id');
        if ($cont > 0) {
            throw new Exception('已有该商品或（商品条码）');
        }

        $data['update_at'] = date('Y-m-d H:i:s');
        if ($id !== 0) {
            // 商品code 不能被修改
            unset($data['code']);
            return $this->db()->where('id', $id)->where('mer_id', $data['mer_id'])->update($data);
        }
        $id = $this->db()->insert($data, true);
        if ($id) {
            $img = array_merge(explode(',', $data['pics']), explode(',', $data['images']));
            updateUploadStatus($img, $id);
        }
        return true;
    }

    /**
     * 列表
     * @param $where |条件
     * @param $list_num |数量
     * @return mixed
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function list($where, $list_num, $field)
    {
        return $this->db()->where($where ?? [])->order('create_at desc,id desc')
            ->field($field)->whereNull('delete_at')->limit($list_num)->select();
    }
}
